package com.itheima.bos.web.action.base;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
@Controller
public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
	
	protected int page;
	protected int rows;
	public void setPage(int page) {
		this.page = page;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}

	// 驱动模型
	protected T model;

	@Override
	public T getModel() {
		// TODO Auto-generated method stub
		return model;

	}

	// 构造方法实例model对象
	public BaseAction() {
		Type genericSuperclass = this.getClass().getGenericSuperclass();
		// 获得第一个泛型参数对象
		ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
		@SuppressWarnings("unchecked")
		Class<T> modelClass = (Class<T>) parameterizedType.getActualTypeArguments()[0];
		// 创建model实例
		try {
			model = modelClass.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
			System.out.println("构造器失败");
		}
	}
	
	protected void getPageValueStack(Page<T> page){
		//将数据提取为服务端可以识别的数据
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("total", page.getTotalElements());
			m.put("rows", page.getContent());
			//将数据要入值栈返回页面
			ActionContext.getContext().getValueStack().push(m);
	}

}
